/*
 * @Date: 2025-01-29 21:27:49
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-10-01 20:22:14
 * @FilePath: /admin-vue/src/plugins/router/index.ts
 */
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import getRoutes from './register'
import type { App } from 'vue'
import { RouteEnum } from '@/enums/RouteEnum'

//获取动态路由
const routes: RouteRecordRaw[] = getRoutes()

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/admin',
    },
    {
      name: '404',
      path: '/404',
      component: () => import('@/components/common/404.vue'),
    },
    {
      name: '403',
      path: '/403',
      component: () => import('@/components/common/403.vue'),
    },
    {
      name: '500',
      path: '/500',
      component: () => import('@/components/common/500.vue'),
    },
    {
      name: 'login',
      path: '/login',
      component: () => import('@/views/login/index.vue'),
    },
    {
      name: 'not-found',
      path: '/:pathMatch(.*)*',
      redirect: '/404',
    },
    ...routes,
  ],
})

const setup = async (app: App) => {
  app.use(router)

  //守卫
  router.beforeEach(async (to, from, next) => {
    // 开始 loadingBar
    window.$loadingBar?.start()

    //登录页面不验证
    if (to.name === RouteEnum.LOGIN) {
      next()
      return
    }

    //验证登录
    if (!useAuth().isLogin()) {
      next({ name: RouteEnum.LOGIN })
      return
    } else {
      //加载菜单数据
      if (useRouteStore().menus.length === 0) {
        //加载菜单数据
        await useRouteStore().getGlobalMenus()
      }

      //加载用户数据
      if (!useUserStore().info) {
        //加载菜单数据
        await useUserStore().getInfo()
      }
    }

    // 外链路由, 从新标签打开，返回上一个路由
    if (to.meta.href) {
      window.open(to.meta.href as string)
      next({ path: from.fullPath, replace: true, query: from.query })
      return
    }
    next()
  })
  router.afterEach(() => {
    // 结束 loadingBar
    window.$loadingBar?.finish()
  })

  await router.isReady()
}

export { setup }
export default router
